# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.


from odoo import api, fields, models, _

from .check_zncspt import check_fapiao


import time


def zncspt_check_method(fapiao):
    # print('zncspt_check_method', fapiao)
    result = check_fapiao(fapiao)

    for rec in result:
        one = fapiao.browse(rec['id'])
        # print('zncspt_check_method. 2.', rec)

        api_check_result = rec['api_check_result']
        api_check_result_info = rec['api_check_result_info']

        values = {
            'zncspt_api_check_result': api_check_result,
            'zncspt_api_check_result_info': api_check_result_info,
        }

        if api_check_result == 'done':
            # one.state  = one['state'] # done, refunded, be_invalid

            api_check_date = rec['api_check_date']
            api_check_count = rec['api_check_count']
            api_list_flag = rec['api_list_flag']

            values.update({
                'zncspt_api_check_date': api_check_date,
                'zncspt_api_check_count': api_check_count,
                'zncspt_api_list_flag': api_list_flag,
            })

        else:
            check_error = api_check_result[0:9]
            if check_error == 'fpi_error':
                values['state'] = rec['state'] = 'error'
            elif check_error == 'api_error':
                values['state'] = 'recheck'
                rec['state'] = 'recheck'

        one.write(values)

    return result


class FapiaoCheckProvider(models.Model):
    _inherit = "fp.check.provider"

    def _request_methods(self):
        result = super()._request_methods()
        result2 = result.copy()
        result2.update({'zncspt': zncspt_check_method})
        return result2


class FapiaoCheck(models.Model):
    _inherit = "fp.fapiao.check"

    zncspt_api_check_result_info = fields.Char('查验结果信息', help="查验结果信息")
    zncspt_api_check_result = fields.Char('查验结果', help="""
      done: 查验正确. 其他:查验错误
    """)

    zncspt_api_check_count = fields.Integer('查验次数')
    zncspt_api_check_date = fields.Date('查验日期')

    zncspt_api_list_flag = fields.Char('清单标志')
